package org.chnxi.study.algorithm.binarysearch;

/**
 * 二分查找（非递归）
 */
public class BinarySearchNoRecur {

    public static void main(String[] args) {
        int[] arr = {1,3,8,10,67,100};
        System.out.println("idx = "+binarySearch(arr , 1));
        System.out.println("idx = "+binarySearch(arr , 8));
        System.out.println("idx = "+binarySearch(arr , 100));
        System.out.println("idx = "+binarySearch(arr , -1));
    }

    /**
     * 二分查找（非递归）
     * @param arr 待查找的升序数组
     * @param target 需要查找的数
     * @return 如果找到，返回索引位，未找到返回-1
     */
    public static int binarySearch(int[] arr , int target){
        int left = 0;
        int right = arr.length - 1;
        while(left <= right){
            int mid = (left + right) / 2;
            if(arr[mid] == target){
                return mid;
            }else if(arr[mid] > target){ //需要向左边查找
                right = mid - 1;
            }else {
                left = mid +1;
            }
        }
        return -1;
    }

}
